import express from 'express';
import http from 'http';
import cors from 'cors';
import helmet from 'helmet';
import dotenv from 'dotenv';
import { initDatabase } from './database/db.js';
import { log } from './utils/logger.js';
import { requestLogger } from './middleware/requestLogger.js';
import { setupSSHWebSocket } from './websocket/sshHandler.js';

// 导入路由
import authRoutes from './routes/auth.js';
import serversRoutes from './routes/servers.js';
import debugRoutes from './routes/debug.js';

// 加载环境变量
dotenv.config();

// 创建Express应用
const app = express();
const server = http.createServer(app);
const PORT = process.env.PORT || 3000;

// 初始化数据库
try {
  initDatabase();
  log.system('数据库初始化成功');
} catch (error) {
  log.error('数据库初始化失败', { error: error.message });
  process.exit(1);
}

// 中间件
app.use(helmet({
  contentSecurityPolicy: false, // WebSocket需要
  crossOriginEmbedderPolicy: false
}));

app.use(cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:5173',
  credentials: true
}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(requestLogger);

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'SSH Web Tool 后端服务运行中',
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/servers', serversRoutes);
app.use('/api/debug', debugRoutes);

// 404处理
app.use((req, res) => {
  log.warn('访问了不存在的路径', { path: req.path });
  res.status(404).json({
    success: false,
    message: '请求的资源不存在'
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  log.error('服务器错误', { 
    error: err.message, 
    stack: err.stack,
    path: req.path 
  });
  
  res.status(err.status || 500).json({
    success: false,
    message: err.message || '服务器内部错误'
  });
});

// 设置WebSocket
setupSSHWebSocket(server);

// 启动服务器
server.listen(PORT, () => {
  log.system(`═══════════════════════════════════════════════`);
  log.system(`🚀 SSH网页工具后端服务启动成功！`);
  log.system(`📡 HTTP服务器: http://localhost:${PORT}`);
  log.system(`🔌 WebSocket服务: ws://localhost:${PORT}/ws/ssh`);
  log.system(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
  log.system(`⏰ 启动时间: ${new Date().toLocaleString('zh-CN')}`);
  log.system(`═══════════════════════════════════════════════`);
});

// 优雅关闭
process.on('SIGTERM', () => {
  log.system('收到SIGTERM信号，准备关闭服务器...');
  server.close(() => {
    log.system('服务器已关闭');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  log.system('收到SIGINT信号，准备关闭服务器...');
  server.close(() => {
    log.system('服务器已关闭');
    process.exit(0);
  });
});

// 未捕获的异常处理
process.on('uncaughtException', (error) => {
  console.error('❌ 未捕获的异常:');
  console.error(error);
  log.error('未捕获的异常', { error: error.message, stack: error.stack });
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('❌ 未处理的Promise拒绝:');
  console.error(reason);
  log.error('未处理的Promise拒绝', { reason, promise });
});

export default app;

